//
//@author jltxseo
// Created by junlintianxia on 2019/4/21.
//
#include <string.h>
#include <jni.h>
#include<malloc.h>
#include <android/log.h>
#include <string>
#include "DataFieldProvider.h"

#define LOG_TAG "ndk.out.c"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)

/*
 * 在Native层操作Java对象，读取/设置属性
 * jobject obj代表执行此JNI操作的类实例引用
 * Class:     com_xq_jltx_javajni_DataFieldProvider
 * Method:    onNativeSetName
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_xq_jltx_javajni_DataFieldProvider_onNativeSetName
        (JNIEnv *env, jobject obj) {
    //获得jfieldID 以及 该字段的初始值
    jfieldID nameFieldId;
    //获得Java层该对象实例的类引用
    jclass cls = env->GetObjectClass(obj);
    //获得属性
    nameFieldId = env->GetFieldID(cls, "name", "Ljava/lang/String;");

    if (nameFieldId == NULL) {
        LOGD("get name field id erro \n");
    }

    // 获得该属性的值
    jstring javaNameStr = (jstring) (env->GetObjectField(obj, nameFieldId));
    //转换为 char *类型
    const char *c_javaName = env->GetStringUTFChars(javaNameStr, NULL);
    //输出显示
    LOGD("the name from java is %s", c_javaName);
    //释放局部引用
    env->ReleaseStringUTFChars(javaNameStr, c_javaName);

    //构造一个jString对象
    char *c_ptr_name = "I come from Native";
    //构造一个jstring对象
    jstring cName = env->NewStringUTF(c_ptr_name);
    // 设置该字段的值
    env->SetObjectField(obj, nameFieldId, cName);

}

/*
 * Class:     com_xq_jltx_javajni_DataFieldProvider
 * Method:    onNativeSetStaticName
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_xq_jltx_javajni_DataFieldProvider_onNativeSetStaticName
        (JNIEnv *env, jobject obj) {
    //1 . 找到java代码的 class文件
    jclass jcls = env->GetObjectClass(obj);
    //2 寻找class里面的属性
    jfieldID jfieldId = env->GetStaticFieldID(jcls, "sName", "Ljava/lang/String;");
    if (jfieldId == NULL) {
        LOGD("get sName field id erro \n");
    }

    //3 获得属性
    jstring javaNameStr = (jstring) env->GetStaticObjectField(jcls, jfieldId);
    //转换为 char *类型
    const char *c_javaName = env->GetStringUTFChars(javaNameStr, NULL);
    //输出显示
    LOGD("the sName from java is %s", c_javaName);
    //释放局部引用
    env->ReleaseStringUTFChars(javaNameStr, c_javaName);
    //构造一个jString对象
    char *c_ptr_name = "I come form Static Native";
    //构造一个jstring对象
    jstring cName = env->NewStringUTF(c_ptr_name);
    // 设置该字段的值
    env->SetStaticObjectField(jcls, jfieldId, cName);
}



